package com.iretailer.report.quartz.init;

import com.iretailer.report.quartz.model.QuartzJobBean;
import com.iretailer.report.util.SpringUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Auther: xjw
 * @Date: 2019/1/23 13:53
 * @Description:
 */
public class QuartTaskUtil {
    private static Logger log = LoggerFactory.getLogger(QuartTaskUtil.class);

    public static void invokMethod(QuartzJobBean scheduleJob) {
        Object object = null;
        Class clazz;

        if (scheduleJob.getSpringId() != null) {
            //springId不为空先按springId查找bean
            object = SpringUtils.getBean(scheduleJob.getSpringId());
        } else if (scheduleJob.getJobClass() != null) {
            //按jobClass查找
            try {
                clazz = Class.forName(scheduleJob.getJobClass());
                object = clazz.newInstance();
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        }

        if (object == null) {
            log.error("任务名称 = [{}]---------------未启动成功，请检查执行类是否配置正确!!", scheduleJob.getJobName());
            return;
        }
        clazz = object.getClass();
        Method method = null;
        try {
            method = clazz.getDeclaredMethod(scheduleJob.getMethodName());
        } catch (NoSuchMethodException e) {
            log.error("任务名称 = [{}]---------------未启动成功，请检查执行类的方法名是否设置错误!!", scheduleJob.getJobName());
            e.printStackTrace();
        }

        if (method != null) {
            try {
                method.invoke(object);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    @AllArgsConstructor
    @Getter
    public enum TASK_STATE {
        NONE("NONE", "unknown"),
        NORMAL("NORMAL", "normal"),
        PAUSED("PAUSED", "pause"),
        COMPLETE("COMPLETE", "complete"),
        ERROR("ERROR", "error"),
        BLOCKED("BLOCKED", "blocked");

        @Setter
        private String value;
        @Setter
        private String des;


    }


}
